package com.bootdo.system.controller;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserOnline;
import com.bootdo.system.service.MenuService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.SessionService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WxUserService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
public class LoginController extends BaseController {

	@Autowired
	MenuService menuService;
	
	@Autowired
	FileService fileService;
	@Autowired
	BootdoConfig bootdoConfig;
	
	@Autowired
	SessionService sessionService;
	@Autowired
	UserService userService;
	@Autowired
	OrderService orderService;
	
	@Autowired
	WxUserService wxUserService;
	
	@Autowired
	private RoleService roleService;

	@GetMapping({ "/", "" })
	String welcome(Model model) { 
		Long userId2 = ShiroUtils.getUserId();
		if(userId2 > 0) {
			return "redirect:/index";
		}
		return "redirect:/login";
	}
	
	@RequestMapping({"/MP_verify_uDaxwCzSZISrHsp2.txt"})
    @ResponseBody
    private String returnConfigFile() {
        return "uDaxwCzSZISrHsp2";
    }
	
//	@Log("请求访问主页")
	@GetMapping("/index")
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if (fileDO != null && fileDO.getUrl() != null) {
			if (fileService.isExist(fileDO.getUrl())) {
				model.addAttribute("picUrl", fileDO.getUrl());
			} else {
				model.addAttribute("picUrl", "/img/Logo.jpg");
			}
		} else {
			model.addAttribute("picUrl", "/img/Logo.jpg");
		}
		model.addAttribute("username", getUser().getUsername());

		return "index";
	}

	@GetMapping("/login")
	String login(Model model,Integer uid) throws UnsupportedEncodingException {
		
		model.addAttribute("uid", uid);
		return "login";
	}

	@SuppressWarnings("rawtypes")
//	@Log("登录")
	@ApiOperation(value="登录接口")
	@ApiImplicitParams({
		@ApiImplicitParam(name="username",value = "用户名",dataType="String"),
		@ApiImplicitParam(name="password",value = "密码",dataType="String"),
		@ApiImplicitParam(name="verify",value = "验证码（暂时不使用）",dataType="String")
	})
	@PostMapping("/login")
	@ResponseBody
	Result ajaxLogin(String username, String password, String verify, HttpServletRequest request,HttpServletResponse resp) throws InterruptedException {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> map=new HashMap<String,Object>();
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
//			String sessionId = (String) subject.getSession().getId();
//            map.put("sessionId",sessionId);
//            System.out.println("sessionId==============="+sessionId);
			map.put("msg", "登录成功!");
			return Result.success(map);
		} catch (AuthenticationException e) {
			return Result.error(CodeMsg.NOT_FIND_USER);
		} /*
			 * catch (UnknownSessionException e) { return
			 * Result.error(CodeMsg.NOT_FIND_USER1); }
			 */
	}

	
	 @GetMapping("/wx/wxLogin")
	    public void doWxLogin (HttpServletRequest request, HttpServletResponse response) {
	        try {
	            userService.doWxLogin(request, response);
	        } catch (Exception e) {
	            e.printStackTrace();
	            //相应的处理
	        }
	 
	    }
	 
	
	@GetMapping("/logout")
	String logout(HttpServletRequest request) {
//		HttpSession session = request.getSession();
//		String id = session.getId();
//		System.out.println("sessionid=============="+id);
		ShiroUtils.logout();
		return "redirect:/login";
	}

	@GetMapping("/main")
	String main() {
		return "main";
	}

	/**
	 * 生成验证码
	 */
	@GetMapping(value = "/getVerify")
	public void getVerify(HttpServletRequest request, HttpServletResponse response) {
		try {
			response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
			response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expire", 0);
			RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
			randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
		} catch (Exception e) {
		}
	}
	
	
	/**
	 *获取用户权限
	 */
	@ResponseBody
	@RequestMapping("/permiss")
	public Set<String>  searchPermiss(HttpServletResponse resp) {
		Set<String> perms=null;
		Long userId = getUserId();
		if(userId != 1) {
			perms = menuService.listPerms(userId);
		}
		return perms;
	}
	
	 @RequestMapping(value = "/unauth")
	    @ResponseBody
	    public Object unauth() {
		 	return Result.error(CodeMsg.NOT_FIND_USER);
	    }
	 
	 
 	@RequestMapping("/mainData")
	@ResponseBody
	public Map<String,Object> list() {
 		Map<String, Object> params=new HashMap<String, Object>();
 		UserDO user = ShiroUtils.getUser();
 		if(user.getUserId() == 1L) {
 			UserDO userDO = userService.get(user.getUserId());
			params.put("qbye", getDouble2String(userDO.getBalance()));
			//今日金额
			String direct2Order = orderService.getDirect2Order(null, DateUtils.format2(new Date()));
			String direct2VipOrder = orderService.getDirect2VipOrder(null, DateUtils.format2(new Date()));
			params.put("jrje", getDouble2String(direct2Order)+getDouble2String(direct2VipOrder));
			//今日佣金
			String fyje = orderService.getProfit2Order(null, DateUtils.format2(new Date()));
			params.put("jryj", getDouble2String(fyje));
			//今日订单数
			int direct2OrderNum = orderService.getDirect2OrderNum(null, DateUtils.format2(new Date()));
			int direct2VipOrderNum = orderService.getDirect2VipOrderNum(user.getUserId().intValue(), DateUtils.format2(new Date()));
			params.put("jrdds", direct2OrderNum+direct2VipOrderNum);
			
			String fyje2 = orderService.getProfit2Order(null, null);
			params.put("zyjs", getDouble2String(fyje2));
			
			//今日会员数
			int num =wxUserService.getNum(null, DateUtils.format4(new Date()));
			params.put("hys", num);
			//总订单数
			int ddzs = orderService.getDirect2OrderNum(null, null);
			int ddzs2 = orderService.getDirect2VipOrderNum(null, null);
			params.put("ddzs", ddzs+ddzs2);
			//总会员数
			int zhys =wxUserService.getNum(null,null);
			params.put("zhys", zhys);
			//总金额数
			String zjes = orderService.getDirect2Order(null, null);
			String zjes2 = orderService.getDirect2VipOrder(null, null);
			params.put("zjes",  getDouble2String((getDouble2String(zjes2)+getDouble2String(zjes))+""));
			//总返佣数
			String zfys = orderService.getProfit2Order2(null, null);
			params.put("zfys", getDouble2String(zfys));
			return params;
 		}
		List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
		boolean falg=false;
		for (RoleDO role : list2) {
			if(role.getRoleId() == 59L) {
				falg=true;
			}
		}
		if(falg) {
			return null;
		}else {
			UserDO userDO = userService.get(user.getUserId());
			params.put("qbye", getDouble2String(userDO.getBalance()));
			//今日金额
			String direct2Order = orderService.getDirect2Order(user.getUserId().intValue(), DateUtils.format2(new Date()));
			String direct2VipOrder = orderService.getDirect2VipOrder(user.getUserId().intValue(), DateUtils.format2(new Date()));
			params.put("jrje", getDouble2String(direct2Order)+getDouble2String(direct2VipOrder));
			//今日佣金
			String fyje = orderService.getProfit2Order(user.getUserId().intValue(), DateUtils.format2(new Date()));
			params.put("jryj", getDouble2String(fyje));
			//今日订单数
			int direct2OrderNum = orderService.getDirect2OrderNum(user.getUserId().intValue(), DateUtils.format2(new Date()));
			int direct2VipOrderNum = orderService.getDirect2VipOrderNum(user.getUserId().intValue(), DateUtils.format2(new Date()));
			params.put("jrdds", direct2OrderNum+direct2VipOrderNum);
			
			String fyje2 = orderService.getProfit2Order(user.getUserId().intValue(), null);
			params.put("zyjs", getDouble2String(fyje2));
			
			//今日会员数
			int num =wxUserService.getNum(user.getUserId().intValue(), DateUtils.format4(new Date()));
			params.put("hys", num);
			//总订单数
			int ddzs = orderService.getDirect2OrderNum(user.getUserId().intValue(), null);
			int ddzs2 = orderService.getDirect2VipOrderNum(user.getUserId().intValue(), null);
			params.put("ddzs", ddzs+ddzs2);
			//总会员数
			int zhys =wxUserService.getNum(user.getUserId().intValue(),null);
			params.put("zhys", zhys);
			//总金额数
			String zjes = orderService.getDirect2Order(user.getUserId().intValue(), null);
			String zjes2 = orderService.getDirect2VipOrder(user.getUserId().intValue(), null);
			params.put("zjes",  getDouble2String((getDouble2String(zjes2)+getDouble2String(zjes))+""));
			//总返佣数
			String zfys = orderService.getProfit2Order2(user.getUserId().intValue(), null);
			params.put("zfys", getDouble2String(zfys));
		}
		return params;
	}
	private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	 
	 
}
